package com.itwang.common;


import cn.hutool.core.net.NetUtil;
import com.itwang.handler.ConsumerException;

import java.util.LinkedHashSet;
//ip地址获取类
public class IpGeter {
	public static LinkedHashSet<String> ipvs() {
		LinkedHashSet<String> strings = NetUtil.localIps();
		return strings;
	}
	
	public static LinkedHashSet<String> screenValidIp(LinkedHashSet<String> ipvs){
		if (ipvs.size() <= 0) {
			throw new ConsumerException("参数错误,不能获取到有效的IP地址");
		}
		LinkedHashSet<String> strings = new LinkedHashSet<String>();
		
		for (String ipv : ipvs) {
			if (!ipv.contains("0:0:0:0:0:0:0:1")
					&& !ipv.contains("127.0.0.1")
					&& !ipv.contains("fe80:")
			) {
				int tail = ipv.indexOf("%");
				if (tail == -1) {
					strings.add(ipv);
				}else {
					strings.add(ipv.substring(0,tail));
				}
			}
		}
		Logger.debug("获取到的ip为" + strings);
		return strings;
	}
	
	public static String getIpString(LinkedHashSet<String> ipvs) {
		if (ipvs.size() <= 0) {
			throw new ConsumerException("参数错误,不能获取到有效的IP地址");
		}
		String result = "";
		for (String ipv : ipvs) {
			
			result += ipv;
			result += "<br>";
			// result += "<tr>";

		}
		return result;
	}
	
	public static String getLocalIpAString() {
		LinkedHashSet<String> ipvs = ipvs();
		LinkedHashSet<String> strings = screenValidIp(ipvs);
		String ipString = getIpString(strings);
		
		return ipString;
	}
}
